﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Common.Util;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Util;
using RestSharp;

namespace pinduoduo
{
    public class G_Api
    {
       
#if DEBUG
        public static string ServerIp = "http://127.0.0.1";
        public static string API_URL = ServerIp + ":8088";
#else
        public static string ServerIp = "http://106.12.151.125";
        public static string API_URL = ServerIp + "/prod-api";
#endif

        public static string MY_IP = "";

        public static string TOKEN = "";

        public static string MACHINECODE = "";

        public static VipUser Cur_VipUser = null;

        public static async Task<IRestResponse> Login(string username, string password, string machineCode,string clientName)
        {
            string url = API_URL + "/clientLogin?machineCode=" + machineCode;
            var restclient =RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");

            request.AddJsonBody(new { username, password, machineCode, clientName });
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }

        public static async Task<IRestResponse> CaptchaImage()
        {
            string url = API_URL + "/captchaImage";
            var restclient =RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");

            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }

        public static async Task<IRestResponse> RegisterUser(ApiUser apiUser, string machineCode, string code, string uuid)
        {
            string url = API_URL + "/pdd/vipUser/register?machineCode=" + machineCode + "&code=" + code + "&uuid=" + uuid;
            var restclient =RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");

            request.AddJsonBody(apiUser);
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }


        public static async Task<IRestResponse> AddOrUpdatePddToken(IEnumerable<PddToken> pddTokenList, string machineCode, string code, string uuid)
        {
            string url = API_URL + "/pdd/vipUser/register?machineCode=" + machineCode + "&code=" + code + "&uuid=" + uuid;
            var restclient = RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");

            //request.AddJsonBody(apiUser);
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }

        /// <summary>
        /// 卡密充值
        /// </summary>
        /// <param name="apiUser"></param>
        /// <param name="machineCode"></param>
        /// <param name="code"></param>
        /// <param name="uuid"></param>
        /// <returns></returns>
        public static async Task<IRestResponse> Recharge(string userName, string card)
        {
            string url = API_URL + "/pdd/vipUser/recharge?machineCode=" + MACHINECODE;
            var restclient =RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");

            request.AddJsonBody(new { card, userName });
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }


        public static async Task<IRestResponse> UpdateMachineCode(string machineCode)
        {
            string url = API_URL + "/pdd/vipUser/updateMachineCode?oldMachineCode=" + MACHINECODE + "&newMachineCode="+ machineCode;
            var restclient = RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 7.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            return response;
        }


        
        public static async Task<IRestResponse> GetMyIp()
        {
            string url = "http://ky.myip.top/";
            var restclient =RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);
                MY_IP = jo["ip"].ToString();

            }
            return response;
        }

        

        public static int GetPddTokenStatus(string pdduid, out string errorMsg)
        {
            errorMsg = "";
            //string url = API_URL + "/pdd/vipUser/getProxyIp";
            string url = API_URL + "/pdd/token/getPddTokenStatus?pdduid=" + pdduid;

            var restclient = RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);

            var response = restclient.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);
                if (jo["code"].ToString() == "200")
                {
                    return 0;
                }
                else if (jo["code"].ToString() == "800")
                {
                    return -1;
                }
                else
                {
                    return 1;
                }
            }
            return 1;
        }

        public static string GetProxyIp(string pdduid,out string errorMsg)
        {
            errorMsg = "";
            //string url = API_URL + "/pdd/vipUser/getProxyIp";
            string url = API_URL + "/pdd/proxy/getProxyIp?pdduid="+ pdduid;

            var restclient = RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);
  
            var response = restclient.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);
                if (jo["code"].ToString() == "200")
                {
                    string ip = jo["data"]["ip"].ToString();
                   
                    string usePassword = jo["data"]["usePassword"].ToString();
                    if (usePassword == "1")
                    {
                        string userName = jo["data"]["userName"].ToString();
                        string password = jo["data"]["password"].ToString();
                       
                        RestClientUtil.isCredentials = true;
                        RestClientUtil.UserName = userName;
                        RestClientUtil.Password = password;
                    }
                    else 
                    {
                        RestClientUtil.isCredentials = false;
                    }
                    //if ("软件到期了" == ip)
                    //{
                    //    return null;
                    //}
                    if (!string.IsNullOrWhiteSpace(ip))
                    {
                        return ip.Replace("\0", "").Replace("\r\n", "");
                    }
                 
                    return null;
                }
                else if (jo["code"].ToString() == "800")
                {
                    errorMsg = jo["msg"].ToString();
                }
                else if (jo["code"].ToString() == "500") 
                {
                    errorMsg = jo["msg"].ToString(); 
                }
            }
            return "";
        }

        public static async Task<VipUser> GetVipUser()
        {
            string url = API_URL + "/pdd/vipUser/getVipInfo";

            var restclient =RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);

            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jo = JObject.Parse(response.Content);
                if (jo["code"].ToString() == "200")
                {
                    var vipUser = jo["vipUser"].ToObject<VipUser>();
                    Cur_VipUser = vipUser;
                    return vipUser;
                }
            }

            return null;
        }

        public static async Task<bool> SoftwareExpire()
        {
            string url = API_URL + "/pdd/vipUser/softwareExpire";

            var restclient =RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);

            request.Timeout = 10000;
            var response = await restclient.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                if (response.Content == "true")
                {
                    return true;
                }
            }
            return false;
        }

        public static async Task<string> GetServerTime()
        {
            string url = API_URL + "/pdd/config/serverTime";

            var restclient =RestClientUtil.CreateRestClient(url);

            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("Authorization", "Bearer " + TOKEN);
            request.AddHeader("client_ip", MY_IP);
            request.AddHeader("machine_code", MACHINECODE);

            request.Timeout = 5000;
            var response = await restclient.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string time = response.Content;
                return time;
            }

            return null;
        }


        public static async Task<string> CheckIp(string daili) 
        {
            //string url = "http://ip-api.com/json";
            string url = "https://www.baidu.com/";

            var restclient = RestClientUtil.CreateRestClient(url);
            restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
         
            var response = await restclient.ExecuteAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return response.Content;
            }

            return null;
        }

        //public static async Task<string> GetServerAvatar()
        //{

        //    string path =  AppDomain.CurrentDomain.BaseDirectory + "avatar";
        //    if (!File.Exists("path"))
        //    {
            
        //    }

        //    //string url = ServerIp + "/download/update/";

        //    //var restclient =RestClientUtil.CreateRestClient(url);

        //    //var request = new RestRequest(Method.GET);
        //    //request.AddHeader("Content-Type", "application/json");
        //    //request.AddHeader("Accept", "application/json, text/javascript, */*");
        //    //request.AddHeader("Accept-Encoding", "gzip, deflate");
        //    //request.AddHeader("Accept-Encoding", "gzip, deflate");
        //    //request.AddHeader("Authorization", "Bearer " + TOKEN);
        //    //request.AddHeader("client_ip", MY_IP);
        //    //request.AddHeader("machine_code", MACHINECODE);

        //    //request.Timeout = 5000;
        //    //var response = await restclient.ExecuteAsync(request);
        //    //if (response.StatusCode == System.Net.HttpStatusCode.OK)
        //    //{
        //    //    string time = response.Content;
        //    //    return time;
        //    //}

        //    //return null;
        //}

    }
}
